//
//  GBTableView.m
//  MoreTableView
//
//  Created by 郭斌 on 15/4/15.
//  Copyright (c) 2015年 郭斌. All rights reserved.
//

#import "GBTableView.h"
#import "GBRequest.h"
#import "MJRefresh.h"
#import "Cell5_1.h"
#import "GBModel.h"
#import "UIImageView+WebCache.h"
#import "GBSingleWebViewController.h"
#import "Reachability.h"
#import "AFNetworking.h"

#define baseUrl @"&method=listFavorite&token="
#define page @"&p="
#define limit @"&limit=10"
#define tid @"&tid="
#define singlePage1 @"http://qinglangyq.com/detail.html?mid="
#define dmid @"&dmid="
#define getTheCountUrl @"&method=getFavoriteCount&token="
#define docidS @"&docId="
#define collectUrl @"&method=add&token="
#define cancleCollectUrl @"&method=deleteFav&token="
#import "SVProgressHUD.h"

@interface GBTableView () <UITableViewDataSource,UITableViewDelegate,GBRequestDelegate>
{
    //记录每个tableview的当前页
    int _currentPage;
    
    BOOL noDataNew; //判断是否应该刷新
    //4.16改
    NSString *refreshUrl; //下拉加载更多的url
    //MBProgressHUD *_hud;
    int allCount; //所有数据的个数
    int limitCount; //现在数据的条数
}

@end

@implementation GBTableView

#pragma mark - 实例化方法
-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self)
    {
//        //收到删除时候
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteAction:) name:@"deleShow" object:nil];
        //收到刷新的通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startRequest) name:@"reloadTheCollectview" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ReportControllerReportSeccess:) name:@"ReportControllerReportSeccessToCollectNoty" object:nil];
//        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.7 target:self selector:@selector(lateeeee) userInfo:nil repeats:NO];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self lateeeee];
        });
        //初始化
        _currentPage = 1;
        limitCount = 10;
        allCount = 20;
        
        self.data = [NSMutableArray array];
        //_url = [NSString string];
        self.rowHeight = 90;
        self.tableFooterView = [[UIView alloc] init];
        self.delegate = self;
        self.dataSource = self;
        [self registerClass:[Cell5_1 class] forCellReuseIdentifier:@"Cell5_1"];
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return self;
}

//#pragma mark - 接收到删除的点击按钮通知
//-(void)deleteAction:(NSNotification *)note
//{
//    NSDictionary *user = [note userInfo];
//    NSString *url = [user objectForKey:@"deletetS"];
//    //NSLog(@"%@",url);
//    int jji = [url intValue];
//    //NSLog(@"%d",jji);
//    [self.data removeObjectAtIndex:jji];
//    [self reloadData];
//}

#pragma mark - 延时
-(void)lateeeee
{
    // 添加传统的下拉刷新
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(startRequest)];
    
    // 马上进入刷新状态
    [self.header beginRefreshing];
    
    // 添加传统的上拉刷新
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    /**
     也可以这样使用
     [self.tableView.header beginRefreshing];
     此时self.tableView.header == self.tableView.legendHeader
     */
}

#pragma mark - 上拉加载更多
-(void)loadMoreData
{
    //判断当前是否有新数据
    if(limitCount < allCount)
    {
        limitCount += 10;
        _currentPage++;
        [self startRequest2];
    }
    else
    {
        [self.footer endRefreshing];
    }
}

#pragma mark - 获取信息的个数
-(void)getTheInformationCount
{
    KDAccount *account = [KDAccountTool account];
    NSString *getTheInformationCount = [NSString stringWithFormat:@"%@%@%@",ServerActionAddr,getTheCountUrl,account.tokens];
    GBRequest *request = [[GBRequest alloc]initWithUrlStr:getTheInformationCount];
    //NSLog(@"getTheCount = %@",getTheInformationCount);
    request.tag = 1;
    request.delegate = self;
    [request startRequestData];
}

#pragma mark - 开始请求数据
-(void)startRequest
{
    //现获取信息个数
    [self getTheInformationCount];
    //重新刷新 重置数据
    limitCount = 10;
    _currentPage = 1;
    //检查当前网络状态
    
    //清空数组
    [self.data removeAllObjects];
    //NSLog(@"基本url:%@",_Jurl);
    GBRequest *request1 = [[GBRequest alloc]initWithUrlStr:_Jurl];
    //NSLog(@"tid = %@",_tidString);
    request1.tag = 1;
    request1.delegate = self;
    [request1 startRequestData];
}

#pragma mark - 上拉加载更多数据
-(void)startRequest2
{
    KDAccount *account = [KDAccountTool account];
    refreshUrl = [NSString stringWithFormat:@"%@%@%@%@%d%@",ServerActionAddr,baseUrl,account.tokens,page,_currentPage,limit];
    //NSLog(@"###2 %@",refreshUrl);
    GBRequest *request1 = [[GBRequest alloc]initWithUrlStr:refreshUrl];
    request1.tag = 1;
    request1.delegate = self;
    [request1 startRequestData];
}

#pragma mark - 数据成功请求完毕
- (void)requestDidFinished:(GBRequest *)request
{
    //NSLog(@"4");
    NSString *str = [[NSString alloc] initWithData:request.requestData encoding:NSUTF8StringEncoding];
    //解析
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    id dataArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSDictionary *jsonDict = nil;
    if ([dataArray isKindOfClass:[NSDictionary class]])
    {
        jsonDict = dataArray;
        //NSLog(@"%@",jsonDict[@"status"]);
    }
    //NSLog(@"%@",jsonDict[@"info"]);
    //数据总个数
    if([jsonDict[@"info"] isKindOfClass:[NSNumber class]])
    {
        id countAll = jsonDict[@"info"];
        allCount = [countAll intValue];
        //NSLog(@"%d",allCount);
        return;
    }
    
    NSMutableArray *info = jsonDict[@"info"];
    for(NSDictionary *dic in info)
    {
        GBModel *model = [[GBModel alloc] init];
        model.date = dic[@"date"];
        model.docId = [NSString stringWithFormat:@"%@", dic[@"docId"]] ;
        model.fav_id = [dic[@"fav_id"] intValue];
        //NSLog(@"%@",dic[@"docId"]);
        model.title = dic[@"title"];
        id favid = dic[@"fav_id"];
        model.fav_id = [favid intValue];
        id typep = dic[@"type"];
        model.type = [typep intValue];
        id uid = dic[@"u_id"];
        model.u_id = [uid intValue];
        model.url = dic[@"url"];
        model.author = dic[@"author"];
        model.authorId = [dic[@"authorId"] integerValue];
        model.sourceName = dic[@"sourceName"];
        model.source = [dic[@"source"] integerValue];
        model.fav_time = [dic[@"fav_time"] integerValue];
        model.report = [dic[@"report"] integerValue];
        [self.data addObject:model];
        //[self reloadData];
    }
    [self reloadData];
    //停止更新数据
    [self.header endRefreshing];
    [self.footer endRefreshing];
    //NSLog(@"%@",jsonDict);
}

#pragma mark - 数据请求失败
- (void)requestDidFailedWithError:(NSError *)error
{
    [SVProgressHUD showErrorWithStatus:@"数据请求失败，请检查网络" maskType:SVProgressHUDMaskTypeGradient];
    
    //停止更新数据
    [self.header endRefreshing];
    [self.footer endRefreshing];
}

#pragma mark - tableview返回行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell5_1";
    Cell5_1 *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    if(self.data.count > 0)
    {
        GBModel *model = self.data[indexPath.row];
        cell.titleLabel1.text = model.title;
        //cell.titleLabel1.font = [UIFont systemFontOfSize:19];
        cell.titleLabel1.font = [UIFont boldSystemFontOfSize:17];
        cell.titleLabel1.textColor = [UIColor colorWithRed:(64.0 / 255.0) green:(64.0 / 255.0) blue:(64.0 / 255.0) alpha:1];
        cell.titleLabel1.frame = CGRectMake(10, -8, self.frame.size.width - 20, 60);
        
        cell.timeLabel.text = model.date;
        cell.timeLabel.font = [UIFont systemFontOfSize:12];
        cell.readBtn.tag = indexPath.row;
        
        NSString *dele = [NSString stringWithFormat:@"%ld%@",(long)indexPath.row,@"Dele"];
        //NSUserDefaults 保存删除按钮的docid
        NSUserDefaults *userDefaults11z = [NSUserDefaults standardUserDefaults];
        //保存数据
        [userDefaults11z setObject:model.docId forKey:dele];
        //同步数据
        [userDefaults11z synchronize];
        //定制cell右按钮
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return cell;
}

#pragma mark - 允许编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    GBModel *model = self.data[indexPath.row];
    NSString *docidd = model.docId;
    //NSLog(@"%@", docidd);
    
    KDAccount *account = [KDAccountTool account];
    
//    //NSLog(@"%ld",(long)sender.tag);
//    NSString *sssss = [NSString stringWithFormat:@"%ld%@",(long)indexPath.row,@"Dele"];
//    //NSUserDefaults
//    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//    //读取数据
//    NSString *str = [userDefaults stringForKey:sssss];
    
    //取消收藏
    NSString *deleteUrl = [NSString stringWithFormat:@"%@%@%@%@%@",ServerActionAddr,cancleCollectUrl,account.tokens,docidS,docidd];
    //NSLog(@"%@", deleteUrl);
    //请求数据
    NSURLRequest *httpReq = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:deleteUrl]];
    
    AFHTTPRequestOperation *reqOper = [[AFHTTPRequestOperation alloc] initWithRequest:httpReq];
    [reqOper setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *op,id success){
        NSHTTPURLResponse *response = [op response];
        NSInteger code = [response statusCode];
        if (code == 200)
        {
            NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[op responseData] options:NSJSONReadingMutableContainers error:nil];
            if([jsonDict[@"status"] isEqualToString:@"ok"])
            {
                [SVProgressHUD showSuccessWithStatus:@"删除成功" maskType:SVProgressHUDMaskTypeGradient];
                
                //从数据源中删除
                [_data removeObjectAtIndex:indexPath.row];
                //从列表中删除
                [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

            }
            //保存失败
            else if ([jsonDict[@"status"] isEqualToString:@"err"])
            {
                [SVProgressHUD showErrorWithStatus:@"发送失败" maskType:SVProgressHUDMaskTypeGradient];
            }
            //已存在
            else if ([jsonDict[@"status"] isEqualToString:@"ext"])
            {
                [SVProgressHUD showErrorWithStatus:@"已存在" maskType:SVProgressHUDMaskTypeGradient];
            }
        }
    } failure:^(AFHTTPRequestOperation *op, NSError *error) {
        if (error) {
            //NSLog(@"req error %@",error);
        }
    }];
    [reqOper start];
}

#pragma mark - 左划删除
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

//cell选中执行
#pragma mark - 当单元格被选中
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger count = self.data.count;
    //跳转单个信息
//    GBSingleWebViewController *single = [[GBSingleWebViewController alloc] init];
    //NSLog(@"$$$");
    if(count != 0)
    {
        GBModel *model = self.data[indexPath.row];
        model.whichPage = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
        NSDictionary *userInfo11b = @{@"GBModel":model};
        [[NSNotificationCenter defaultCenter] postNotificationName:@"goToTheSingleView" object:nil userInfo:userInfo11b];
    }
}

#pragma mark - 通知接收区
- (void)ReportControllerReportSeccess:(NSNotification *)noty{
    NSString *docid = noty.userInfo[@"docid"];
    int i = 0;
    for (GBModel *model in self.data) {
        if ([docid isEqualToString: model.docId]) {
            
            model.report = YES;
            [self.data replaceObjectAtIndex:i withObject:model];
            return;
        }
        i++;
    }
}
@end